import { createStore } from "vuex";
import { INCREMENT_N } from "./mutation-types";
import axios from "axios";

const store = createStore({
  state() {
    return {
      counter: 0,
      name: "why",
      age: 18,
      books: [
        { name: "深入Vuejs", price: 200, count: 3 },
        { name: "深入Webpack", price: 240, count: 5 },
        { name: "深入React", price: 130, count: 1 },
        { name: "深入Node", price: 220, count: 2 },
      ],
      discount: 0.6,
      banners: [],
    };
  },

  getters: {
    totalPrice(state, getters) {
      let totalPrice = 0;
      for (const book of state.books) {
        totalPrice += book.count * book.price;
      }
      return totalPrice * getters.currentDiscount;
    },
    currentDiscount(state) {
      return state.discount * 0.9;
    },
    totalPriceCoutGreaterN(state, getters) {
      return function(n) {
        let totalPrice = 0;
        for (const book of state.books) {
          if (book.count > n) {
            totalPrice += book.count * book.price;
          }
        }
        return totalPrice * getters.currentDiscount;
      };
    },
    nameInfo(state) {
      return `name: ${state.name}`;
    },
    ageInfo(state) {
      return `age: ${state.age}`;
    },
  },

  mutations: {
    increment(state) {
      state.counter++;
    },
    decrement(state) {
      state.counter--;
    },
    [INCREMENT_N](state, payload) {
      state.counter += payload.n;
    },
    addBannerDate(state, payload) {
      state.banners = payload;
    },
  },

  actions: {
    incrementAction(context, payload) {
      console.log(context);

      console.log(payload.count);
      setTimeout(() => {
        context.commit("increment");
      }, 1000);
    },
    getHomeMultiData(context) {
      return new Promise((resolve, reject) => {
        axios
          .get("http://123.207.32.32:8000/home/multidata")
          .then((res) => {
            context.commit("addBannerDate", res.data.data.banner.list);
            resolve(res.data.data.banner.list);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
  },
});

export default store;
